<?php

class Controller_Default extends Controller_Abstract
{
    function actionIndex()
    {
		$cam = $this->_context->cam;
		$pub = $this->_context->pub;
		$pla = $this->_context->pla;
		$cus = $this->_context->cus;
		$cre = $this->_context->cre;
		$ind = $this->_context->ind;
		
		$x = $this->_context->x;
		$y = $this->_context->y;
		if(!empty($x)){
			$_SESSION['x'] = $x;
			$_SESSION['y'] = $y;
		}
		if (!empty($cam))
		{
			$params = array();
			$params['cam'] = $cam;
			$params['pub'] = $pub;
			$params['pla'] = $pla;
			$params['cre'] = $cre;
			$params['ind'] = $ind;
			if (empty($cus))
			{
				$params['cus'] = '';
			}
			else
			{
				$params['cus'] = $cus;
			}
			$_SESSION['campaign'] = $params;
		}
		$this->_view['showmonkey'] = true;
		
		//TODO: recording home views
		
		if(!isset($_SESSION['self_redirect'])){
			if ($user = $this->_app->currentUser())
			{
				$record = new Record($user['id']);
				$record->addHomeViewRecording();
			}
	    	else
			{
				// record anonymous users' landing
				
				if(isset($this->_context->cam) && !isset($_COOKIE['anonym']))
				{
					$this->_context->_domain = $this->_site['domain'];
					$this->_context->_game = $this->_site['game'];
					
					$record = new Record('', $this->_context);
					$record->addLandingRecording();
					
					setcookie('anonym', session_id(), time()+60*60*24*30, '/', COOKIE_DOMAIN, 0, 1);
				}
				
				// record user info for short reg
				$infos = array();
				if (isset($this->_context->gender)) {
					$infos['gender'] = ucwords($this->_context->get('gender'));
				}
				if (isset($this->_context->fname)) {
					$infos['fname'] = $this->_context->get('fname');
				}
				if (isset($this->_context->lname)) {
					$infos['lname'] = $this->_context->get('lname');
				}
				if (isset($this->_context->email)) {
					$infos['email'] = $this->_context->get('email');
				}
				if (isset($this->_context->birthday)) {
					$infos['birthday'] = $this->_context->get('birthday');
				}
				if (count($infos) > 0) {
					$_SESSION['accountinfo'] = $infos;
				}
				
			}
		}else{
			unset($_SESSION['self_redirect']);
		}
		

		if(!empty($cam) || !empty($pub) || !empty($pla) || !empty($cus) || !empty($cre) || !empty($ind) || !empty($x) || !empty($y)){
			$_SESSION['self_redirect'] = true;
			return $this->_redirect(url('default/index'));
		}	
		
		if(isset($_SESSION['x'])){
			$this->_view['x'] = $_SESSION['x'];
			$this->_view['y'] = $_SESSION['y'];
			unset($_SESSION['x'], $_SESSION['y']);
		}
		
		
		$domain = $this->_view['site']['domain'];
		$tipModel = new TipManager();
		$tipArray = $tipModel->getTipByFields( array('domain' => $domain, 'controller_view' => 'default_index') );
		$this->_view['tips'] = isset($tipArray[$domain]['default_index'])? $tipArray[$domain]['default_index'] : array();
    	if(!isset($_COOKIE['credittip'])){
			setcookie('credittip', 'new', time()+60*60*24*365*10);
		}
		
		if(isset($this->_view['user']) && strtolower($this->_site['locale']) == 'us'){
			$rewardModel = new Reward();
			$credits = $rewardModel->getUserRewards($this->_view['user']['id']);
			if($credits){
				switch(strtolower($this->_site['name'])){
					case 'lalaloot.com':
						$showMaumduCredits = 50;
						break;
					default:
						$showMaumduCredits = 15;
						break;
				}
				if($credits < $showMaumduCredits){
				//	$this->_view['showMaumdu'] = true;
				$this->_view['showMaumdu'] = false;
				}
			}
		}
		
		return $this->display($this->_site['template']);
    }
	function actionHealth()
	{
//		$d = $this->_context->d;
//		$redis = RedisConnection::getRedis();
//		$i = 0;
//		while ($record = $redis->lPop('timeframe:' . $d))
//		{
//			$i++;
//			$a = $redis->hGetAll($record);
//			$redis->del($record);
//		}
//		$redis->del('timeframe:' . $d);
		exit;
	}
	
	function actionEmailPixel()
	{
		header('Content-Type: image/gif');
		echo base64_decode('R0lGODlhAQABAJAAAP8AAAAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw==');
		if ($emailId = $this->_context->get('pla'))
		{
			$emailModel = new Email();
			// only update email open_time at the first time
			$emailOpenTimeDate = $emailModel->getEmailOpenTimeDate($emailId);
			if ($emailOpenTimeDate == '0000-00-00 00:00:00' || $emailOpenTimeDate == '0000-00-00' || $emailOpenTimeDate == '')
			{
				$record = new Record('', $this->_context);
				$record->addRefEmailOpen();
				$emailModel->updateEmailOpenTime($emailId);
				
				$email = $emailModel->getEmailInfoById($emailId);
				if(!empty($email)){
					$email_created_hour = $email['created'] - $email['created'] % (60*60);
					
					$record = new Record('', $this->_context);
					$record->addEmailOpenRecording($email['email_type'], date('YmdHis', $email_created_hour));
				}
			}
		}
		
		exit();
	}
	
	// redirect email offer to right link and record it
	function actionOfferstat() {
		if (!isset($this->_context->emailId) || !isset($this->_context->offer)) {
			header(Util::HTTPStatus(500));
			exit;
		}
		$emailId = $this->_context->get('emailId');
		$offerField = $this->_context->get('offer');
		$emailLinksModel = new EmailLinks();
		if ($link = $emailLinksModel->getRedirectUrl($emailId, $offerField)) {
			//check whether some offer links in this email already has been redirected, if none, record current time as redirect date
			$offerOrder = $offerField[5];
			if (($redirectDate = $emailLinksModel->offerLinksIsRedirected($emailId)) == '0000-00-00 00:00:00') {
				$emailLinksModel->setRedirectDate($emailId, $offerOrder);
			} else {
				$emailLinksModel->addRedirectNum($emailId, $offerOrder);
			}
			$emailModel = new Email();
			$email = $emailModel->getEmailInfoById($emailId);
			if(!empty($email)){
				$email_created_hour = $email['created'] - $email['created'] % (60*60);
				
				$record = new Record('', $this->_context);
				$record->addEmailClickRecording($email['email_type'], date('YmdHis', $email_created_hour));
			}
			header('Location: ' . $link);
		}
	}
	
	function actionBluebarofferclick()
	{
		if(!isset($this->_view['user'])){
			return $this->_redirect(url('default/index'));
		}
		
		$blueBarOfferId = $this->_context->get('bluebarofferid', false);
		if($blueBarOfferId){
			$blueBarOfferModel = new BlueBarOffer();
			$blueBarOffer = $blueBarOfferModel->getBlueBarOfferById($blueBarOfferId);
			$formatedUid = Util::getFormattedUserId($blueBarOffer['partner_name'], $this->_view['user']['id'], $this->_site['domain']);
			$blueBarOffer['link'] = str_replace(
				'INSERT_END_USER_ID', 
				$formatedUid, 
				$blueBarOffer['link']
			);
			$blueBarOffer['link'] .= str_replace(
				'[[bluebar_id]]', 
				$blueBarOffer['id'], 
				Util::getParamsOfLinkUrl($blueBarOffer['partner_name'], 'bluebar')
			);
			$record = new Record('', $this->_context);
			$record->addBlueBarOfferClickRecording($blueBarOffer['id']);			
			
			return $this->_redirect($blueBarOffer['link']);
		}
	}
	
	function actionBannerofferclick()
	{
		if(!isset($this->_view['user'])){
			return $this->_redirect(url('default/index'));
		}
		
		$bannerOfferId = $this->_context->get('bannerofferid', false);
		if($bannerOfferId){
			$bannerOfferModel = new BannerOffers();
			$bannerOffer = $bannerOfferModel->getBannerOfferById($bannerOfferId);
			$bannerOffer['link_url'] = str_replace(
				array('INSERT_END_USER_ID', 'INSERT_END_USER_EMAIL'), 
				array($this->_view['user']['id'], $this->_view['user']['email']),
				$bannerOffer['link_url']
			);
			$bannerOffer['link_url'] .= str_replace(
				'[[banner_id]]', 
				$bannerOffer['id'], 
				Util::getParamsOfLinkUrl($bannerOffer['partner_name'], 'banner')
			);
			$record = new Record('', $this->_context);
			$record->addBannerOfferClickRecording($bannerOffer['id']);			
			
			return $this->_redirect($bannerOffer['link_url']);
		}
	}
	
	function actionDailydealsclick()
	{
		if(!isset($this->_view['user'])){
			return $this->_redirect(url('default/index'));
		}
		
		$dailyDealsId = $this->_context->get('dailydealsid', false);
		if($dailyDealsId){
			$dailyDealsModel = new DailyDeals();
			$dailyDealsOffer = $dailyDealsModel->getDailyDealsOfferById($dailyDealsId);
			$formatedUid = Util::getFormattedUserId($dailyDealsOffer['partner_name'], $this->_view['user']['id'], $this->_site['domain']);
			$dailyDealsOffer['link_url'] = str_replace(
				'INSERT_END_USER_ID', 
				$formatedUid, 
				$dailyDealsOffer['link_url']
			);
			$dailyDealsOffer['link_url'] .= str_replace(
				'[[dailydeals_id]]', 
				$dailyDealsOffer['id'], 
				Util::getParamsOfLinkUrl($dailyDealsOffer['partner_name'], 'dailydeals')
			);
			$record = new Record('', $this->_context);
			$record->addDailyDealsOfferClickRecording($dailyDealsOffer['id']);			
			
			return $this->_redirect($dailyDealsOffer['link_url']);
		}
	}
	
	function actionServer()
	{
		print_r($_SERVER);
		exit;
	}
	
	function actionLandingpage()
    {
		$cam = $this->_context->cam;
		$pub = $this->_context->pub;
		$pla = $this->_context->pla;
		$cus = $this->_context->cus;
		$cre = $this->_context->cre;
		$ind = $this->_context->ind;
		
		$x = $this->_context->x;
		$y = $this->_context->y;
		if(!empty($x)){
			$_SESSION['x'] = $x;
			$_SESSION['y'] = $y;
		}
		if (!empty($cam))
		{
			$params = array();
			$params['cam'] = $cam;
			$params['pub'] = $pub;
			$params['pla'] = $pla;
			$params['cre'] = $cre;
			$params['ind'] = $ind;
			if (empty($cus))
			{
				$params['cus'] = '';
			}
			else
			{
				$params['cus'] = $cus;
			}
			$_SESSION['campaign'] = $params;
		}
		$this->_view['showmonkey'] = true;
		
		//TODO: recording home views
		
		if(!isset($_SESSION['self_redirect'])){
			if ($user = $this->_app->currentUser())
			{
				$record = new Record($user['id']);
				$record->addHomeViewRecording();
			}
	    	else
			{
				// record anonymous users' landing
				
				if(isset($this->_context->cam) && !isset($_COOKIE['anonym']))
				{
					$this->_context->_domain = $this->_site['domain'];
					$this->_context->_game = $this->_site['game'];
					
					$record = new Record('', $this->_context);
					$record->addLandingRecording();
					
					setcookie('anonym', session_id(), time()+60*60*24*30, '/', COOKIE_DOMAIN, 0, 1);
				}
				
				// record user info for short reg
				$infos = array();
				if (isset($this->_context->gender)) {
					$infos['gender'] = ucwords($this->_context->get('gender'));
				}
				if (isset($this->_context->fname)) {
					$infos['fname'] = $this->_context->get('fname');
				}
				if (isset($this->_context->lname)) {
					$infos['lname'] = $this->_context->get('lname');
				}
				if (isset($this->_context->email)) {
					$infos['email'] = $this->_context->get('email');
				}
				if (isset($this->_context->birthday)) {
					$infos['birthday'] = $this->_context->get('birthday');
				}
				if (count($infos) > 0) {
					$_SESSION['accountinfo'] = $infos;
				}
				
			}
		}else{
			unset($_SESSION['self_redirect']);
		}
		

		if(!empty($cam) || !empty($pub) || !empty($pla) || !empty($cus) || !empty($cre) || !empty($ind) || !empty($x) || !empty($y)){
			$_SESSION['self_redirect'] = true;
			return $this->_redirect(url('default/landingpage'));
		}	
		
		if(isset($_SESSION['x'])){
			$this->_view['x'] = $_SESSION['x'];
			$this->_view['y'] = $_SESSION['y'];
			unset($_SESSION['x'], $_SESSION['y']);
		}
		
		
		$domain = $this->_view['site']['domain'];
		$tipModel = new TipManager();
		$tipArray = $tipModel->getTipByFields( array('domain' => $domain, 'controller_view' => 'default_index') );
		$this->_view['tips'] = isset($tipArray[$domain]['default_index'])? $tipArray[$domain]['default_index'] : array();
    	if(!isset($_COOKIE['credittip'])){
			setcookie('credittip', 'new', time()+60*60*24*365*10);
		}
		
		if(isset($this->_view['user']) && strtolower($this->_site['locale']) == 'us'){
			$rewardModel = new Reward();
			$credits = $rewardModel->getUserRewards($this->_view['user']['id']);
			if($credits){
				switch(strtolower($this->_site['name'])){
					case 'lalaloot.com':
						$showMaumduCredits = 50;
						break;
					default:
						$showMaumduCredits = 15;
						break;
				}
				if($credits < $showMaumduCredits){
				//	$this->_view['showMaumdu'] = true;
				$this->_view['showMaumdu'] = false;
				}
			}
		}
		
    	if (isset($_SESSION['errors']))
		{
			$errors = $_SESSION['errors'];
			$this->_view['errors'] = $errors;
			unset($_SESSION['errors']);
		}
		if (isset($_SESSION['accountinfo'])) {
			$this->_view['accountinfo'] = $_SESSION['accountinfo'];
			if (isset($this->_view['accountinfo']['birthday']) && QValidator::validate_is_date($this->_view['accountinfo']['birthday'])) {
				$value = $this->_view['accountinfo']['birthday'];
				if (strpos($value, '-') !== false) {
		            $p = '-';
		        } elseif (strpos($value, '/') !== false) {
		            $p = '\/';
		        }
		        $birthday = explode($p, $this->_view['accountinfo']['birthday']);
				unset($this->_view['accountinfo']['birthday']);
				$this->_view['accountinfo']['birthYear'] = $birthday[0];
				$this->_view['accountinfo']['birthMonth'] = $birthday[1];
				$this->_view['accountinfo']['birthDay'] = $birthday[2];
			}
			unset($_SESSION['accountinfo']);
		}

		return $this->display($this->_site['template']);
    }
}

